// 切片
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Collapse, Button } from 'antd-mobile';
import { InbizIcon } from '@inbiz/utils';
import { ICategorySelect } from './content';
import { ISearchData } from '../../../designer/service';
import { TextWidget, getMessage } from '@inbiz/react';

export type IOnRender =  {
  showList: ISearchData['SectionList'];
  selected: string[];
  onSelected: (key: string[], checked: boolean, isAll: boolean, IsWhether: boolean) => void
  onOk: (level?: number) => void
}

function Category({
  list,
  selected,
  onSelected,
  onRender
}: {
  list: ISearchData['SectionList'];
  selected: string[];
  onSelected: ICategorySelect;
  onRender?: (data:IOnRender) => JSX.Element
}) {
  const [categorySelected, $categorySelected] = useState(selected || []);
  useEffect(() => {
    $categorySelected(selected)
  }, [selected]);

  const defaultActiveKey = useMemo(() => {
    let retainItem = list.filter(item => !item.IsGroup).map(e => e.Key);
    let whitherItem = list.filter(item => item.IsGroup);
    whitherItem.forEach((item) => {
      const whitherItemEle = item.SectionGroupData.map((ele, index) => {
        return ele.Key=`${ele.Key}${index}` 
      });
      retainItem = [... retainItem, ...whitherItemEle]
    });
    return  retainItem
  }, [list]);

  const showList = useMemo(() => {
    return list.map((item) => {
      if (item.sectionItemList?.length) {
        return {
          ...item,
          sectionItemList: [
            {
              Key: item.Key + ':',
              isAll: true,
              Value: getMessage('SearchResultEngine.whole'),
            },
            ...item.sectionItemList,
          ],
        } as ISearchData['SectionList'][number];
      } else {
        return item;
      }
    });
  }, [list]);

  //IsWhether 是否为多选
  const handleSelected = useCallback(
    (key: string[], checked: boolean, isAll: boolean, IsWhether: boolean) => {
      if (isAll && !checked) {
        // 全部不能取消选中， 是根据子选项自动计算来的
        return;
      }
      $categorySelected((selected) => {
        if (isAll) {
          return selected.filter((select) => select.indexOf(key[0]) === -1);
        } else {
          if (checked) {
            if (IsWhether) {
              // 多选
              return [...selected, ...key];
            } else {
              // 单选
              const categoryKey = key[0].split(':')[0] + ':';
              return [...selected.filter((select) => select.indexOf(categoryKey) === -1), key[0]];
            }
          } else {
            return selected.filter((select) => select.indexOf(key[0]) === -1);
          }
        }
      });
    },
    [],
  );
  const handleOk = useCallback(() => {
    onSelected(categorySelected);
  }, [onSelected, categorySelected]);
  const handleReset = useCallback(() => {
    $categorySelected([]);
  }, [selected]);

  const getPanel = (item, key) => {
    return (
      <Collapse.Panel title={item.Value} key={key}>
        {item.sectionItemList.map((data) => (
          <CategoryItem
            key={data.Key}
            item={data as ISearchData['SectionList'][number]['sectionItemList'][number]}
            onSelected={handleSelected}
            IsWhether={item.IsWhether}
            selected={
              'isAll' in data && data.isAll
                ? !categorySelected.find((item) => item.includes(data.Key))
                : categorySelected.includes(data.Key)
            }
          />
        ))}
      </Collapse.Panel>
    );
  };
  if (onRender) {
    return onRender({showList, selected: categorySelected, onSelected:handleSelected, onOk: handleOk})
  }
  return (
    <div className="searchResult-categoryBox">
      <div className="categoryContent">
        {!!showList?.length && (
          <Collapse
            defaultActiveKey={defaultActiveKey}
            arrow={<InbizIcon type="icon-ic-arrow-down-bold" />}
          >
            {showList.map((item) => {
              if (item.IsGroup) {
                 return item.SectionGroupData.map((ele) =>  getPanel({ ...item, ...ele }, ele.Key)
                 );
              }
              return getPanel(item, item.Key);
            })}
          </Collapse>
        )}
      </div>
      <div className="categoryFooter">
        <Button className="resetBtn" onClick={handleReset}>
          <TextWidget>SearchResultEngine.reset</TextWidget>
        </Button>
        <Button color="primary" onClick={handleOk}>
          <TextWidget>SearchResultEngine.confirm</TextWidget>
        </Button>
      </div>
    </div>
  );
}

export default Category;

function CategoryItem({
  selected,
  item,
  onSelected,
  IsWhether,
}: {
  item: ISearchData['SectionList'][number]['sectionItemList'][number] & { isAll?: boolean };
  selected: boolean;
  onSelected: (key: string[], checked: boolean, isAll: boolean, IsWhether: boolean) => void;
  IsWhether: boolean;
}) {
  return useMemo(() => {
    const html = `<a class="categoryItem">${item.Value}</a>`;
    return (
      <div
        className={`categoryItemBox ${selected ? 'selected' : ''}`}
        dangerouslySetInnerHTML={{ __html: html }}
        onClick={() => onSelected([item.Key], !selected, !!item.isAll, IsWhether)}
      />
    );
  }, [selected, item, onSelected]);
}